<?php

/**
 * CelebrioMail EmailSeznamCZ
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioMail
 */
namespace ApplicationsModule\MailModule\Providers;

use \Nette\Object;
use \ApplicationsModule\MailModule\MailServer;
use \ApplicationsModule\MailModule\MailReceiver;

/**
 * Email Seznam.cz - mail provider class
 *
 * @author Celebrio Software
 */
class EmailSeznamCZ extends Object implements IProvider {
    
    /* @var MailServer */
    private $mailServer;
    
    /**
     * Mail Server entity
     *
     * @author Celebrio Software
     * @param string $address (e.g. my@seznam.cz)
     * @param string $password (e.g. M1ghty^Pa22w0rd)
     */
    public function __construct($address,$password) {
	$at_sign_pos = strpos($address, "@");
	$provider = strtolower(substr($address, $at_sign_pos+1));
	if($provider != "seznam.cz") throw new \InvalidStateException("Email Seznam.cz provider called on invalid e-mail address.");
	$user = strtolower(substr($address, 0, $at_sign_pos));
	$this->mailServer = new MailServer(
		NULL,
		$user,
		$password,
		$address,
		"imap.seznam.cz",
		"imap",
		993,
		TRUE,
		"smtp.seznam.cz",
		25,
		FALSE);
    }
    
    /**
     * gets MailServer object containing Email Seznam.cz entity
     * @return MailServer 
     */
    public function getMailServer() {
	return $this->mailServer;
    }
    
    /**
     * checks connection using IMAP and POP3 protocol, it doesn't check SMTP as
     * we assume it is correct
     * @return boolean
     */
    public function checkConnection() {
	$mailReceiver = new MailReceiver($this->mailServer);
	if ($mailReceiver->connect()) {
	    $folders = $mailReceiver->getMailFolders();
	    $this->mailServer->setSentFolder($folders["Sent"]);
	    $this->mailServer->setDraftsFolder($folders["Drafts"]);
	    $this->mailServer->setTrashfolder($folders["Trash"]);
	    $this->mailServer->setSpamfolder($folders["Spam"]);
	    $mailReceiver->close();
	    return true;
	} else { // we couldn't connect using imap so we try pop3
	    $this->mailServer->setInProtocol("pop3");
	    $this->mailServer->setInServer("pop3.seznam.cz");
	    $this->mailServer->setInPort("110");
	    $mailReceiver = new MailReceiver($this->mailServer);
	    if($mailReceiver->connect()){
		$mailReceiver->close();
		return true;
	    } else {
		return false;
	    }
	}
    }
    
}